package com.baitiaojun.security.core.handler;

import com.baitiaojun.common.domain.model.result.CommonResult;
import com.baitiaojun.common.enums.impl.ServerExpEnums;
import com.baitiaojun.common.exception.ServerException;
import com.baitiaojun.common.utils.servlet.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 资源拒绝访问处理器, 401
 */
@Slf4j
@Component
public class AuthDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) {
        String requestURI = request.getRequestURI();
        String message = accessDeniedException.getMessage();
        log.warn("请求地址'{}', 异常原因'{}'", requestURI, message);
        ServerExpEnums serverExpEnums = ServerExpEnums.EXP_LOGIN_REPEAT;
        ServletUtils.render(response, CommonResult.error(serverExpEnums.getCode(), serverExpEnums.getName()));
    }
}
